/**
   Copyright 2013 Фроловский А. В.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This file is a part of MyStats project
 */

package foo.mystats.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import foo.mystats.db.DbOpenHelper;
import foo.mystats.db.RowTable;

public class RowContentProvider extends ContentProvider {
  private DbOpenHelper dbOpenHelper;

  private static final int ROWS = 10;
  private static final int ROW_ID = 20;

  private static final String AUTHORITY = "foo.mystats.contentprovider.RowContentProvider";

  private static final String BASE_PATH = "rows";
  public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);

  private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  static {
    sURIMatcher.addURI(AUTHORITY, BASE_PATH, ROWS);
    sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", ROW_ID);
  }

  @Override
  public boolean onCreate() {
    dbOpenHelper = new DbOpenHelper(getContext());
    return false;
  }

  @Override
  public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    queryBuilder.setTables(RowTable.TABLE_ROW);

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case ROWS:
        break;
      case ROW_ID:
        queryBuilder.appendWhere(RowTable.COLUMN_ID + "=" + uri.getLastPathSegment());
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
  }

  @Override
  public String getType(Uri uri) {
    return null;
  }

  @Override
  public Uri insert(Uri uri, ContentValues values) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    long id = 0;

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case ROWS:
        id = db.insert(RowTable.TABLE_ROW, null, values);
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return Uri.parse(BASE_PATH + "/" + id);
  }

  @Override
  public int delete(Uri uri, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    int rowsDeleted = 0;
    
    // TODO Если версия SQLite < 3.6.19, то там нет внешних ключей, и надо
    // вручную данные из data удалять

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case ROWS:
        rowsDeleted = db.delete(RowTable.TABLE_ROW, selection, selectionArgs);
        break;
      case ROW_ID:
        String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(selection)) {
          rowsDeleted = db.delete(RowTable.TABLE_ROW,
              RowTable.COLUMN_ID + "=" + id,
              null);
        } else {
          rowsDeleted = db.delete(RowTable.TABLE_ROW,
              RowTable.COLUMN_ID + "=" + id + " and " + selection,
              selectionArgs);
        }
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return rowsDeleted;
  }

  @Override
  public int update(Uri uri, ContentValues values, String selection,
      String[] selectionArgs) {

    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    int rowsUpdated = 0;

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
      case ROWS:
        rowsUpdated = db.update(RowTable.TABLE_ROW, values, selection, selectionArgs);
        break;
      case ROW_ID:
        String id = uri.getLastPathSegment();
        if (TextUtils.isEmpty(selection)) {
          rowsUpdated = db.update(RowTable.TABLE_ROW,
              values,
              RowTable.COLUMN_ID + "=" + id,
              null);
        } else {
          rowsUpdated = db.update(RowTable.TABLE_ROW,
              values,
              RowTable.COLUMN_ID + "=" + id + " and " + selection,
              selectionArgs);
        }
        break;
      default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return rowsUpdated;
  }
}
